 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=80 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:38 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Replace a substring
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='substring,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Replace a substring</div>

<div class='main-body'>
 
<br><b>Static Replacement</b>
<p>Replacing one static <a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html'>String</a> with another can be done in various ways :
<br>
<PRE>

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ReplaceSubstring {
  
  <span class='comment'>/**
  *  Simplest in Java 1.5, using the replace method, which 
  *  takes CharSequence objects.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> String replace15(
    String aInput, String  aOldPattern, String aNewPattern
  ){
    <span class='keyword'>return</span> aInput.replace(aOldPattern, aNewPattern);
  }

  <span class='comment'>/**
  * Not quite as simple in Java 1.4. The replaceAll method works, 
  * but requires more care, since it uses regular expressions, which 
  * may contain special characters.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> String replace14(
    String aInput, String aOldPattern, String aNewPattern
  ){

    <span class='comment'>/*
    * The replaceAll method is a bit dangerous to use.
    * The aOldPattern is converted into a regular expression.
    * Thus, if aOldPattern may contain characters which have
    * special meaning to regular expressions, then they must
    * be 'escaped' before being passed to replaceAll. It is
    * easy to forget to do this.
    *
    * In addition, aNewPattern treats '$' as special characters 
    * as well: they refer to 'back references'.
    */</span>
    <span class='keyword'>return</span> aInput.replaceAll(aOldPattern, aNewPattern);
    <span class='comment'>/*
    Here is an alternative implementation using Pattern and Matcher,
    which is preferred when the same pattern is used repeatedly
    final Pattern pattern = Pattern.compile( aOldPattern );
    final Matcher matcher = pattern.matcher( aInput );
    return matcher.replaceAll( aNewPattern );
    */</span>
  }

  <span class='comment'>/**
  * If Java 1.4 is unavailable, the following technique may be used.
  *
  * @param aInput is the original String which may contain substring aOldPattern
  * @param aOldPattern is the non-empty substring which is to be replaced
  * @param aNewPattern is the replacement for aOldPattern
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> String replaceOld(
    <span class='keyword'>final</span> String aInput,
    <span class='keyword'>final</span> String aOldPattern,
    <span class='keyword'>final</span> String aNewPattern
  ){
     <span class='keyword'>if</span> ( aOldPattern.equals(<span class='literal'>""</span>) ) {
        <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Old pattern must have content."</span>);
     }

     <span class='keyword'>final</span> StringBuffer result = <span class='keyword'>new</span> StringBuffer();
     <span class='comment'>//startIdx and idxOld delimit various chunks of aInput; these
</span>     <span class='comment'>//chunks always end where aOldPattern begins
</span>     <span class='keyword'>int</span> startIdx = <span class='literal'>0</span>;
     <span class='keyword'>int</span> idxOld = <span class='literal'>0</span>;
     <span class='keyword'>while</span> ((idxOld = aInput.indexOf(aOldPattern, startIdx)) >= <span class='literal'>0</span>) {
       <span class='comment'>//grab a part of aInput which does not include aOldPattern
</span>       result.append( aInput.substring(startIdx, idxOld) );
       <span class='comment'>//add aNewPattern to take place of aOldPattern
</span>       result.append( aNewPattern );

       <span class='comment'>//reset the startIdx to just after the current match, to see
</span>       <span class='comment'>//if there are any further matches
</span>       startIdx = idxOld + aOldPattern.length();
     }
     <span class='comment'>//the final chunk will go to the end of aInput
</span>     result.append( aInput.substring(startIdx) );
     <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>/** Example: update an ip address appearing in a link.  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String[] aArguments) {
    String OLD_IP = <span class='literal'>"45.23.102.12"</span>;
    <span class='comment'>//escape the  '.', a special character in regular expressions
</span>    String OLD_IP_REGEX = <span class='literal'>"45&#092;&#092;.23&#092;&#092;.102&#092;&#092;.12"</span>;
    String NEW_IP = <span class='literal'>"99.104.106.95"</span>;
    String LINK = <span class='literal'>"http://45.23.102.12:8080/index.html"</span>;
    
    log(<span class='literal'>"Old link : "</span> + LINK);
    
    String newLink = replace15(LINK, OLD_IP, NEW_IP);
    log(<span class='literal'>"New link with Java 1.5 replace: "</span> + newLink);
    
    newLink = replace14(LINK, OLD_IP_REGEX, NEW_IP);
    log(<span class='literal'>"New link with Java 1.4 replaceAll: "</span> + newLink);

    newLink = replaceOld(LINK, OLD_IP, NEW_IP);
    log(<span class='literal'>"New link with oldest style: "</span> + newLink);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(String aMessage){
    System.out.println(aMessage);
  }
} 
</PRE>
<br>
<br>Example run of this class :
<PRE>
Old link : http://45.23.102.12:8080/index.html
New link with Java 1.5 replace: http://99.104.106.95:8080/index.html
New link with Java 1.4 replaceAll: http://99.104.106.95:8080/index.html
New link with oldest style: http://99.104.106.95:8080/index.html
</PRE>

<p><b>Dynamic Replacement</b>
<p>If replacement string is not fixed, and needs to be created dynamically,
then another approach is required. In the following example, strings of
the form "<tt>href=Topic182.cjp</tt>" are replaced with a corresponding
string "<tt>href=#182</tt>".
<p>The number <tt>182</tt> is taken only as an example. It is in fact extracted
dynamically, and referenced in the replacement string using the back reference
"<tt>$1</tt>", where <tt>1</tt> is the index of the matching group for
these digits.
<br>
<PRE>

<span class='keyword'>import</span> java.util.regex.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ReplaceSubstringDynamically {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String[] aArguments) {
    String htmlText = <span class='literal'>"&lt;a href=&#092;"Topic27.cjp&#092;"&gt;xyz&lt;/a&gt; blah &lt;a href=Topic8.cjp&gt;abc&lt;/a&gt;"</span>;
    System.out.println(<span class='literal'>"Old HTML text : "</span> + htmlText);
    System.out.println(<span class='literal'>"New HTML text : "</span> + replaceLinks(htmlText));
  }

  <span class='comment'>/**
  * Replace the document links in a snippet of HTML with corresponding
  * fragment links, which start with the # sign, and refer to labelled
  * locations within a single document.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> String replaceLinks(String aHtmlTextWithLinks){
    Pattern pattern = Pattern.compile(fLINK);
    Matcher matcher = pattern.matcher(aHtmlTextWithLinks);
    <span class='keyword'>return</span> matcher.replaceAll(fFRAGMENT);
  }

  <span class='comment'>/**
  * The single matching group of this regex are the digits ((?:&#092;&#092;d){1,3}),
  * which correspond to group 1.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> String fLINK = <span class='literal'>"href=(?:&#092;"|&#092;')?Topic((?:&#092;&#092;d){1,3})&#092;&#092;.cjp(?:&#092;"|&#092;')?"</span>;

  <span class='comment'>/**
  * The "$1" refers to matching group 1 of fLINK (the digits).
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> String fFRAGMENT = <span class='literal'>"href=#$1"</span>;
} 
</PRE>
<br>
<br>Example run of this class :
<p><tt>Old HTML text : &lt;a href="Topic27.cjp">xyz&lt;/a> blah &lt;a href=Topic8.cjp>abc&lt;/a></tt>
<br><tt>New HTML text : &lt;a href=#27>xyz&lt;/a> blah &lt;a href=#8>abc&lt;/a></tt>
<p>Here is a second example, where the replacement string is computed without
using back references.
<br>
<PRE>

<span class='keyword'>import</span> java.util.regex.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ReplaceSubstringAppendReplacement {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String[] aArguments) {
    String text = <span class='literal'>"Apples and oranges are better for all."</span>;
    System.out.println(<span class='literal'>"Old text : "</span> + text);
    System.out.println(<span class='literal'>"New text : "</span> + getEditedText(text));
  }

  <span class='comment'>/**
  * Replace all words starting with the letter 'a' or 'A' with
  * their uppercase forms.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> String getEditedText(String aText){
    StringBuffer result = <span class='keyword'>new</span> StringBuffer();
    Matcher matcher = fINITIAL_A.matcher(aText);
    <span class='keyword'>while</span> ( matcher.find() ) {
      matcher.appendReplacement(result, getReplacement(matcher));
    }
    matcher.appendTail(result);
    <span class='keyword'>return</span> result.toString();
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Pattern fINITIAL_A = Pattern.compile(
    <span class='literal'>"(?:&#092;&#092;s|^)a(?:&#092;&#092;w)*"</span>,
    Pattern.CASE_INSENSITIVE
  );

  <span class='keyword'>private</span> <span class='keyword'>static</span> String getReplacement(Matcher aMatcher){
    <span class='keyword'>return</span> aMatcher.group(<span class='literal'>0</span>).toUpperCase();
  }

} 
</PRE>
<br>
<br>Example run of this class :
<p><tt>Old text : Apples and oranges are better for all.
<br>New text : APPLES AND oranges ARE better for ALL.</tt>

<P><b>Warning</b>
<br>The methods :
<ul>
<li><tt>String.<a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)'>replaceAll(String, String)</a></tt>
<li><tt>String.<a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)'>replaceFirst(String, String)</a></tt>
<li><tt>Matcher.<a  href='http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#appendReplacement(java.lang.StringBuffer,%20java.lang.String)'>appendReplacement(StringBuffer, String)</a></tt>
</ul>
treat <tt>'$'</tt> and <tt>'\'</tt> in the replacement text as special characters. 
If the replacement text can contain arbitrary text, then these characters will usually be escaped using 
<tt>Matcher.<a href='http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#quoteReplacement(java.lang.String)'>quoteReplacement(String)</a></tt>.
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActionba81-2.html?Id=96'>Escape special characters</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='80'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=80 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:38 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
